package cn.edu.zjut.mina.service.impl;

import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.edu.zjut.mina.bean.StandardFormat;
import cn.edu.zjut.mina.po.UserInfo;
import cn.edu.zjut.mina.protocal.JMessageProtocalRes;
import cn.edu.zjut.mina.protocal.ProtocalRegulation;
import cn.edu.zjut.mina.repository.UserInfoRepository;
import cn.edu.zjut.mina.service.IRoomCardService;
import cn.edu.zjut.mina.util.GsonUtils;
import cn.edu.zjut.mina.util.ResultInfoConstUtils;
import cn.edu.zjut.mina.util.UserMap;
@Service("roomCardService")
public class RoomCardServiceImpl implements IRoomCardService{

	/**
	 * 用于存放用户信息的集合
	 */
	private final UserMap userMap = UserMap.getInstance();
	
	@Autowired
	private UserInfoRepository userInfoRepository;
	
	public JMessageProtocalRes getRoomCard(StandardFormat inJson,
			IoSession session) {
		// TODO Auto-generated method stub
		System.out.println("execute --GetRoomCard()-- method.");
		JMessageProtocalRes res = new JMessageProtocalRes();
		StandardFormat outJson = new StandardFormat();
		String datas;
		UserInfo user;
		if (userMap.get(inJson.userId) == null || userMap.get(inJson.userId).user == null) {
			System.out.println("未知错误");
			outJson.userId = inJson.userId;
			outJson.resultInfo = ResultInfoConstUtils.GETROOMCARD_USERNULLINFO;
			outJson.result = false;
		} else {
			user = userMap.get(inJson.userId).user;
			synchronized(user) {//参考java编程思想 689页
				Integer roomCard = userInfoRepository.findByUserId(inJson.userId).getRoomCardNum();
				user.setRoomCardNum(roomCard);
				outJson.userId = inJson.userId;
				outJson.roomcardnum = user.getRoomCardNum();
				outJson.result = true;
			}
		}
		
		res.setResultCode(ProtocalRegulation.GETROOMCARD);
		datas = GsonUtils.beanToJson(outJson).trim();
		res.setContent(datas);
		return res;
	}

}
